﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Uniblocks;

public class PlayerCtrl : MonoBehaviour
{
    public GameObject selectObj;
    public ushort selectBlockId;
    public VoxelInfo selectVoxelInfo;
    public AudioSource asr;
    // Use this for initialization
    void Start()
    {
        selectObj = GameObject.Find("selectObj");
        selectBlockId = 3;
    }

    // Update is called once per frame
    void Update()
    {
        VoxelInfo info = Engine.VoxelRaycast(GameManager.instance.mainCamera.transform.position, GameManager.instance.mainCamera.transform.forward,
            SettingsManager.CameraRange, false);
        if (info != null)
        {
            selectObj.SetActive(true);
            selectObj.transform.position = Engine.VoxelInfoToPosition(info);



            if (Input.GetMouseButton(0))
            {
                Wa(info);
            }
            else
            {

            }
            if (Input.GetMouseButtonDown(1))
            {
                if (info.adjacentIndex.y - info.index.y == 1 && info.GetVoxel() == 2)
                {
                    info.SetVoxel(1, false);
                }
                PlaceVoxel(new VoxelInfo(info.adjacentIndex, info.chunk));
            }
        }
        else
        {
            selectObj.SetActive(false);
        }
        selectVoxelInfo = info;
    }

    void DestroyVoxel(VoxelInfo info)
    {
        ushort id = info.GetVoxel();
        Vector3 pos = info.chunk.VoxelIndexToPosition(info.index);
        SoundUtl.PlayDestroyPlaceSound(id, pos);

        Debug.Log(info.chunk.VoxelIndexToPosition(info.index));
        Voxel.DestroyBlock(info);
    }

    void PlaceVoxel(VoxelInfo info)
    {
        Vector3 pos = info.chunk.VoxelIndexToPosition(info.index);
        SoundUtl.PlayDestroyPlaceSound(selectBlockId, pos);
        Voxel.PlaceBlock(info, selectBlockId);
    }

    #region 挖
    private float wat = 0;
    void Wa(VoxelInfo info)
    {
        if (selectVoxelInfo == null)
        {
            wat = 0;
            return;
        }
        if (info.index.IsEqual(selectVoxelInfo.index) && info.GetVoxel() == selectVoxelInfo.GetVoxel())
        {
            wat += Time.deltaTime;

            if (wat > DataManager.instance.blockDic[info.GetVoxel()].destroyTime)
            {
                wat = 0;
                DestroyVoxel(info);
            }
        }
        else
        {
            wat = 0;
        }
    }
    #endregion
}
